We start by loading the required packages. ggplot2 is included in the tidyverse package.
If not still in the workspace, load the data we saved in the previous lesson.
Now, in order to generate a more informative set of visualizations, let’s focus in on just two of the CNC cities, San Francisco and LA:
ggplot2ggplot2 is a plotting package that makes it simple to create complex plots from data in a data frame. It provides a more programmatic interface for specifying what variables to plot, how they are displayed, and general visual properties. Therefore, we only need minimal changes if the underlying data change or if we decide to change from a bar plot to a scatter plot. This helps in creating publication quality plots with minimal amounts of adjustments and tweaking.
ggplot2 functions like data in the ‘long’ format, i.e., a column for every dimension, and a row for every observation. Well-structured data will save you lots of time when making figures with ggplot2
ggplot graphics are built step by step by adding new elements. Adding layers in this fashion allows for extensive flexibility and customization of plots.
To build a ggplot, we will use the following basic template that can be used for different types of plots:
ggplot(data = <DATA>, mapping = aes(<MAPPINGS>)) + <GEOM_FUNCTION>()
ggplot() function and bind the plot to a specific data frame using the data argumentaes) function), by selecting the variables to be plotted and specifying how to present them in the graph, e.g. as x/y positions or characteristics such as size, shape, color, etc.add ‘geoms’ for graphical representations of the data in the plot (points, lines, bars). ggplot2 offers many different geoms; we will use some common ones today, including:
* `geom_point()` for scatter plots, dot plots, etc.
* `geom_boxplot()` for, well, boxplots!
* `geom_line()` for trend lines, time series, etc. To add a geom to the plot use the + operator. Because we have two continuous variables, let’s use geom_point() first:
The + in the ggplot2 package is particularly useful because it allows you to modify existing ggplot objects. This means you can easily set up plot templates and conveniently explore different types of plots, so the above plot can also be generated with code like this:
# Assign plot to a variable
coords_plot <- ggplot(data = CNC_2019_data_SF_LA),
mapping = aes(x = longitude, y = latitude))
# Draw the plot
coords_plot +
geom_point()Notes
ggplot() function can be seen by any geom layers that you add (i.e., these are universal plot settings). This includes the x- and y-axis mapping you set up in aes().ggplot() function.+ sign used to add new layers must be placed at the end of the line containing the previous layer. If, instead, the + sign is added at the beginning of the line containing the new layer, ggplot2 will not add the new layer and will return an error message.# This is the correct syntax for adding layers
coords_plot +
geom_point()
# This will not add the new layer and will return an error message
coords_plot
+ geom_point()Challenge (optional)
Scatter plots can be useful exploratory tools for small datasets. For data sets with large numbers of observations, such as the
surveys_completedata set, overplotting of points can be a limitation of scatter plots. One strategy for handling such settings is to use hexagonal binning of observations. The plot space is tessellated into hexagons. Each hexagon is assigned a color based on the number of observations that fall within its boundaries. To use hexagonal binning withggplot2, first install the R packagehexbinfrom CRAN:
Building plots with ggplot2 is typically an iterative process. We start by defining the dataset we’ll use, lay out the axes, and choose a geom:
Then, we start modifying this plot to extract more information from it. For instance, we can add transparency (alpha) to avoid overplotting:
ggplot(data = CNC_2019_data_SF_LA, mapping = aes(x = longitude, y = latitude)) +
geom_point(alpha = 0.5)We can also add colors for all the points:
ggplot(data = CNC_2019_data_SF_LA, mapping = aes(x = longitude, y = latitude)) +
geom_point(alpha = 0.5, color = "blue")Or to color each species in the plot differently, you could use a vector as an input to the argument color. ggplot2 will provide a different color corresponding to different values in the vector. Here is an example where we color with taxon_kingdom_name:
ggplot(data = CNC_2019_data_SF_LA, mapping = aes(x = longitude, y = latitude)) +
geom_point(alpha = 0.5, aes(color = taxon_kingdom_name))We can also specify the colors directly inside the mapping provided in the ggplot() function. This will be seen by any geom layers and the mapping will be determined by the x- and y-axis set up in aes().
ggplot(data = CNC_2019_data_SF_LA, mapping = aes(x = longitude, y = latitude, color = taxon_kingdom_name)) +
geom_point(alpha = 0.5)Notice that we can change the geom layer and colors will be still determined by taxon_kingdom_name
ggplot(data = CNC_2019_data_SF_LA, mapping = aes(x = longitude, y = latitude, color = taxon_kingdom_name)) +
geom_jitter(alpha = 0.5)Barplots are often the best way to display counts of different categories, or levels, of a categorical variable.
Before we generate a barplot, let’s first summarize the data in a meaninful way.
CNC_2019_observation_counts <- CNC_2019_data_SF_LA %>%
group_by(city, taxon_kingdom_name) %>%
summarize(num_observations = n()) %>%
dplyr::filter(complete.cases(taxon_kingdom_name))
CNC_2019_observation_countsNow, we can start by making a boxplot of the number of species observed in each city:
ggplot(data = CNC_2019_observation_counts, mapping = aes(x = city, y = num_observations)) +
geom_bar(stat = "identity")Note, that the argumet stat = “identity” tells geom_bar to use the counts provided in the data, instead of generating counts of the number of cases at each x. Let’s go one step further and plot the number of species observed in each city:
ggplot(data = CNC_2019_observation_counts, mapping = aes(x = city, y = num_observations, group = taxon_kingdom_name, fill = taxon_kingdom_name)) +
geom_bar(stat = "identity")The default behavior is to stack the bars, but it is often useful to have bars side by side. To do this we use the argument position=position_dodge() inside geom_bar()
ggplot(data = CNC_2019_observation_counts, mapping = aes(x = city, y = num_observations, group = taxon_kingdom_name, fill = taxon_kingdom_name)) +
geom_bar(stat = "identity", position=position_dodge())If we want to emphasize the comparison between cities within each kingdom, we can do this.
ggplot(data = CNC_2019_observation_counts, mapping = aes(x = taxon_kingdom_name, y = num_observations, group = city, fill = city)) +
geom_bar(stat = "identity", position=position_dodge())We can use boxplots to visualize the distribution (not just the counts) of observations among different categories. Let’s make a boxplot of the latitude of observations made in each city:
Challenge
Boxplots are useful summaries, but hide the shape of the distribution. For example, if the distribution is bimodal, we would not see it in a boxplot. An alternative to the boxplot is the violin plot, where the shape (of the density of points) is drawn.
- Replace the box plot with a violin plot; see
geom_violin()
Let’s calculate number of observations per day for each city.
Time series data can be visualized as a line plot with day (or any other unit of time) on the x axis and counts on the y axis:
Unfortunately, this does not work because we plotted data for both cities together. We need to tell ggplot to draw a line for each city by modifying the aesthetic function to include group = city:
ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = n, group = city)) +
geom_line()We will be able to distinguish species in the plot if we add colors (using color also automatically groups the data):
ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = n, color = city)) +
geom_line()ggplot2 has a special technique called faceting that allows the user to split one plot into multiple plots based on a factor included in the dataset. We will use it to make a time series plot for each kingdom:
CNC_2019_daily_counts <- CNC_2019_data_SF_LA %>%
count(city, observed_on, taxon_kingdom_name) %>%
filter(complete.cases(taxon_kingdom_name))ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = n, color = city)) +
geom_line() +
facet_wrap(~ taxon_kingdom_name)Usually plots with white background look more readable when printed. We can set the background to white using the function theme_bw(). Additionally, you can remove the grid:
ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = n, color = city)) +
geom_line() +
facet_wrap(~ taxon_kingdom_name) +
theme_bw() +
theme(panel.grid = element_blank())ggplot2 themesIn addition to theme_bw(), which changes the plot background to white, ggplot2 comes with several other themes which can be useful to quickly change the look of your visualization. The complete list of themes is available at https://ggplot2.tidyverse.org/reference/ggtheme.html. theme_minimal() and theme_light() are popular, and theme_void() can be useful as a starting point to create a new hand-crafted theme.
The ggthemes package provides a wide variety of options (including an Excel 2003 theme). The ggplot2 extensions website provides a list of packages that extend the capabilities of ggplot2, including additional themes.
Challenge
Use what you just learned to create a plot that depicts how the total number of distinct species observed (remember n_distinct?) changes over the four days in each city.
Answer
CNC_2019_daily_counts <- CNC_2019_data_SF_LA %>% group_by(city, observed_on, taxon_kingdom_name) %>% summarise(num_species = n_distinct(taxon_species_name)) %>% filter(complete.cases(taxon_kingdom_name)) ggplot(data = CNC_2019_daily_counts, mapping = aes(x=observed_on, y = num_species, color = city)) + geom_line() + facet_wrap(~ taxon_kingdom_name) + theme_bw()![]()
The facet_wrap geometry extracts plots into an arbitrary number of dimensions to allow them to cleanly fit on one page. On the other hand, the facet_grid geometry allows you to explicitly specify how you want your plots to be arranged via formula notation (rows ~ columns; a . can be used as a placeholder that indicates only one row or column).
Let’s modify the previous plot to compare how the weights of males and females have changed through time:
# One column, facet by rows
CNC_2019_daily_counts <- CNC_2019_data_SF_LA %>%
group_by(city, observed_on, taxon_kingdom_name) %>%
summarise(num_species = n_distinct(taxon_species_name)) %>%
filter(complete.cases(taxon_kingdom_name))
ggplot(data = CNC_2019_daily_counts,
mapping = aes(x = observed_on, y = num_species, group = city, color = city)) +
geom_line() +
facet_grid(taxon_kingdom_name ~ .)# One row, facet by column
ggplot(data = CNC_2019_daily_counts,
mapping = aes(x = observed_on, y = num_species, group = city, color = city)) +
geom_line() +
facet_grid(. ~ taxon_kingdom_name)Take a look at the ggplot2 cheat sheet, and think of ways you could improve the plot.
Now, let’s change names of axes to something more informative than ‘observed_on’ and ‘n’ and add a title to the figure:
ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = num_species, color = city)) +
geom_line() +
facet_wrap(~ taxon_kingdom_name) +
labs(title = "Species observed during CNC 2019",
x = "Day",
y = "Number of species") +
theme_bw()The axes have more informative names, but their readability can be improved by increasing the font size:
ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = num_species, color = city)) +
geom_line() +
facet_wrap(~ taxon_kingdom_name) +
labs(title = "Species observed during CNC 2019",
x = "Day",
y = "Number of species") +
theme_bw() +
theme(text=element_text(size = 16))Note that it is also possible to change the fonts of your plots. If you are on Windows, you may have to install the extrafont package, and follow the instructions included in the README for this package.
After our manipulations, you may notice that the values on the x-axis are still not properly readable. Let’s change the orientation of the labels and adjust them vertically and horizontally so they don’t overlap. You can use a 90-degree angle, or experiment to find the appropriate angle for diagonally oriented labels:
ggplot(data = CNC_2019_daily_counts, mapping = aes(x = observed_on, y = num_species, color = city)) +
geom_line() +
facet_wrap(~ taxon_kingdom_name) +
labs(title = "Species observed during CNC 2019",
x = "Day",
y = "Number of species") +
theme_bw() +
theme(axis.text.x = element_text(colour = "grey20", size = 12, angle = 90, hjust = 0.5, vjust = 0.5),
axis.text.y = element_text(colour = "grey20", size = 12),
text = element_text(size = 16))If you like the changes you created better than the default theme, you can save them as an object to be able to easily apply them to other plots you may create:
grey_theme <- theme(axis.text.x = element_text(colour = "grey20", size = 12, angle = 90, hjust = 0.5, vjust = 0.5),
axis.text.y = element_text(colour = "grey20", size = 12),
text = element_text(size = 16))
ggplot(CNC_2019_data_SF_LA, aes(x = longitude, y = latitude)) +
geom_hex() +
grey_themeChallenge
With all of this information in hand, please take another five minutes to either improve one of the plots generated in this exercise or create a beautiful graph of your own. Use the RStudio
ggplot2cheat sheet for inspiration. Here are some ideas:
- See if you can change the thickness of the lines.
- Can you find a way to change the name of the legend? What about its labels?
- Try using a different color palette (see http://www.cookbook-r.com/Graphs/Colors_(ggplot2)/).
Faceting is a great tool for splitting one plot into multiple plots, but sometimes you may want to produce a single figure that contains multiple plots using different variables or even different data frames. The gridExtra package allows us to combine separate ggplots into a single figure using grid.arrange():
library(gridExtra)
spatial_plot <- ggplot(CNC_2019_data_SF_LA, aes(x = longitude, y = latitude)) +
geom_hex() +
theme_bw() +
annotate("text", x = c(-122.5, -119.8), y = c(36.5, 33), label = c("San Francisco", "Los Angeles"))
temporal_plot <- CNC_2019_data_SF_LA %>%
count(city, observed_on) %>%
ggplot(mapping = aes(x = observed_on, y = n, color = city)) +
geom_line() +
theme_bw() +
xlab("Day") + ylab("Number of observations")
grid.arrange(spatial_plot, temporal_plot, nrow = 2, ncol = 1, heights = c(6, 6))In addition to the ncol and nrow arguments, used to make simple arrangements, there are tools for constructing more complex layouts.
After creating your plot, you can save it to a file in your favorite format. The Export tab in the Plot pane in RStudio will save your plots at low resolution, which will not be accepted by many journals and will not scale well for posters.
Instead, use the ggsave() function, which allows you easily change the dimension and resolution of your plot by adjusting the appropriate arguments (width, height and dpi).
Make sure you have the fig_output/ folder in your working directory.
spatial_plot <- ggplot(CNC_2019_data_SF_LA, aes(x = longitude, y = latitude)) +
geom_hex() +
theme_bw() +
annotate("text", x = c(-122.5, -119.8), y = c(36.5, 33), label = c("San Francisco", "Los Angeles"))
ggsave("figures/spatial_plot.png", spatial_plot, width = 15, height = 10)
# This also works for grid.arrange() plots
combo_plot <- grid.arrange(spatial_plot, temporal_plot, nrow = 2, ncol = 1, heights = c(12, 12))
ggsave("figures/combo_spatiotemporal_plot.png", combo_plot, height = 12, dpi = 300)Note: The parameters width and height also determine the font size in the saved plot.
Page built on: <U+0001F4C6> 2020-06-19 <U+2012> <U+0001F562> 11:39:29